package com.cruise.game.service.impl.agent;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.mapper.AgentMapper;
import com.cruise.game.mapper.GameCategoryMapper;
import com.cruise.game.mapper.OrderMapper;
import com.cruise.game.model.entity.Agent;
import com.cruise.game.model.entity.GameCategory;
import com.cruise.game.model.param.agent.AgentUpdateParam;
import com.cruise.game.model.vo.agent.AgentProfileVO;
import com.cruise.game.service.agent.AgentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理信息服务实现
 *
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class AgentServiceImpl implements AgentService {

    @Resource
    private AgentMapper agentMapper;

    @Resource
    private GameCategoryMapper gameCategoryMapper;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public AgentProfileVO getAgentProfile(Long userId) {
        // 查询代理信息
        Agent agent = agentMapper.selectOne(
                new LambdaQueryWrapper<Agent>()
                        .eq(Agent::getUserId, userId)
                        .last("LIMIT 1"));

        if (agent == null) {
            throw new ApiException("您尚未成为代理，请先通过'/api/user/apply-agent'接口申请成为代理，或联系管理员处理");
        }

        return convertToAgentProfileVO(agent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgentProfileVO updateAgentProfile(Long userId, AgentUpdateParam param) {
        // 查询代理信息
        Agent agent = agentMapper.selectOne(
                new LambdaQueryWrapper<Agent>()
                        .eq(Agent::getUserId, userId)
                        .last("LIMIT 1"));

        if (agent == null) {
            throw new ApiException("代理信息不存在");
        }

        // 更新代理信息
        agent.setServicePrice(param.getServicePrice());
        agent.setDescription(param.getDescription());
        agent.setUpdatedAt(LocalDateTime.now());

        // 更新数据库
        agentMapper.updateById(agent);

        return convertToAgentProfileVO(agent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAgentStatus(Long userId, String status) {
        if (!Arrays.asList("available", "busy").contains(status)) {
            throw new ApiException("无效的状态值");
        }

        // 查询代理信息
        Agent agent = agentMapper.selectOne(
                new LambdaQueryWrapper<Agent>()
                        .eq(Agent::getUserId, userId)
                        .last("LIMIT 1"));

        if (agent == null) {
            throw new ApiException("代理信息不存在");
        }

        // 更新状态
        agent.setStatus(status);
        agent.setUpdatedAt(LocalDateTime.now());

        return agentMapper.updateById(agent) > 0;
    }

    @Override
    public Map<String, Object> getAgentStatistics(Long userId) {
        // 查询代理信息
        Agent agent = agentMapper.selectOne(
                new LambdaQueryWrapper<Agent>()
                        .eq(Agent::getUserId, userId)
                        .last("LIMIT 1"));

        if (agent == null) {
            throw new ApiException("代理信息不存在");
        }

        Map<String, Object> statistics = new HashMap<>();

        // 总接单数
        int totalOrders = agent.getOrdersCompleted();
        statistics.put("totalOrders", totalOrders);

        // 待处理订单数
        int pendingOrders = orderMapper.countPendingOrdersByAgentId(agent.getId());
        statistics.put("pendingOrders", pendingOrders);

        // 进行中订单数
        int inProgressOrders = orderMapper.countInProgressOrdersByAgentId(agent.getId());
        statistics.put("inProgressOrders", inProgressOrders);

        // 评分
        BigDecimal rating = agent.getRating();
        statistics.put("rating", rating);

        // 总收入
        BigDecimal totalIncome = orderMapper.sumIncomeByAgentId(agent.getId());
        statistics.put("totalIncome", totalIncome != null ? totalIncome : BigDecimal.ZERO);

        // 本月收入
        BigDecimal monthlyIncome = orderMapper.sumMonthlyIncomeByAgentId(agent.getId());
        statistics.put("monthlyIncome", monthlyIncome != null ? monthlyIncome : BigDecimal.ZERO);

        return statistics;
    }

    /**
     * 转换为代理个人信息VO
     */
    private AgentProfileVO convertToAgentProfileVO(Agent agent) {
        AgentProfileVO vo = new AgentProfileVO();
        BeanUtils.copyProperties(agent, vo);

        // 设置游戏分类信息
        GameCategory gameCategory = gameCategoryMapper.selectById(agent.getGameCategoryId());
        if (gameCategory != null) {
            AgentProfileVO.GameCategoryInfo categoryInfo = new AgentProfileVO.GameCategoryInfo();
            categoryInfo.setId(gameCategory.getId());
            categoryInfo.setName(gameCategory.getName());
            vo.setGameCategory(categoryInfo);
        }

        return vo;
    }
}